<template>
  <j-modal :title="title" :width="1300" :visible="visible" switchFullscreen @cancel="handleCancel" :footer="null">
    <a-spin :spinning="loading">
      <div class="content">
        <a-card title="基本信息">
          <a-form-model :model="form" ref="form" :rules="rules" :label-col="{ span: 7 }" :wrapper-col="{ span: 16 }">
            <a-row>
              <a-col :span="6">
                <a-form-model-item label="方案编码" prop="schemeCode">
                  <a-input :value="form.schemeCode" readOnly> </a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="方案名称" required prop="schemeName">
                  <a-input v-model="form.schemeName" :readOnly="isDisabled" :placeholder="compPlaceholderInput">
                  </a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="适用范围" prop="scope">
                  <a-input v-if="isDisabled" :value="$filterDictTextByCache('appScope', form.scope)" readOnly></a-input>
                  <a-select v-else v-model="form.scope" placeholder="请选择" style="width: 100%" allowClear>
                    <a-select-option v-for="(item, key) in rangeOpts" :key="key" :value="item.value"
                      >{{ item.title }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="是否有效" prop="status">
                  <a-input :value="$filterDictTextByCache('yn', form.status)" readOnly></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="6">
                <a-form-model-item label="总 分" required prop="totalScore">
                  <a-input v-model="form.totalScore" :readOnly="isDisabled" :placeholder="compPlaceholderInput">
                  </a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="6" v-if="isDisabled">
                <a-form-model-item label="创建人" prop="createBy">
                  <a-input v-model="form.createBy" :readOnly="isDisabled" :placeholder="compPlaceholderInput">
                  </a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="6" v-if="isDisabled">
                <a-form-model-item label="创建时间" prop="createTime">
                  <a-input v-model="form.createTime" :readOnly="isDisabled" :placeholder="compPlaceholderInput">
                  </a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="11" class="col-3">
                <a-form-model-item label="方案说明" prop="remark">
                  <a-textarea
                    v-model="form.remark"
                    :readOnly="isDisabled"
                    :rows="3"
                    :placeholder="compPlaceholderInput"
                  ></a-textarea>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-card>
        <a-card title="指标信息" class="index-card">
          <div class="index-top" v-if="showType !== '3'">
            <a-button class="btn" @click="onSelIndex">选择指标</a-button>
            <a-button type="primary" class="ant-btn-danger" style="margin-left: 8px" @click="onDel">删除</a-button>
          </div>
          <div class="index-con">
            <div class="index-left">
              <a-tree
                v-if="treeData.length"
                :checkable="!isDisabled"
                :tree-data="treeData"
                v-model:checkedKeys="checkedKeys"
                :defaultExpandAll="true"
              >
                <template #title="row">
                  <span style="color: #1890ff" @click="indexDetail(row)">{{ row.title }}</span>
                  <!-- <span v-else>{{ row.title }}</span> -->
                </template>
              </a-tree>
            </div>
            <div class="index-right">
              <div class="tit">指标详情</div>
              <a-form-model :model="formByIndex" :rules="rules" :label-col="{ span: 8 }" :wrapper-col="{ span: 14 }">
                <a-row>
                  <a-col :span="11">
                    <a-form-model-item label="指标名称" prop="indicatorName">
                      <a-input :value="formByIndex.indicatorName" readOnly> </a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="11">
                    <a-form-model-item label="上级目录/上级指标" prop="seniorIndicatorName">
                      <a-input :value="formByIndex.seniorIndicatorName" readOnly> </a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="11">
                    <a-form-model-item label="指标类型" prop="indicatorType">
                      <a-input
                        :value="$filterDictTextByCache('indicator', formByIndex.indicatorType)"
                        readOnly
                      ></a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="11">
                    <a-form-model-item label="加/减分基数（P）" prop="addCardinalNumber">
                      <a-input :value="formByIndex.addCardinalNumber" readOnly> </a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="11">
                    <a-form-model-item label="任务量（Y）" prop="taskNumber">
                      <a-input
                        v-model="formByIndex.taskNumber"
                        :readOnly="isDisabled"
                        :placeholder="compPlaceholderInput"
                      >
                      </a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="11">
                    <a-form-model-item label="基 数（Z）" prop="cardinalNumber">
                      <a-input :value="formByIndex.cardinalNumber" readOnly> </a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="11">
                    <a-form-model-item label="是否可修正得分" prop="isScoreCorrection">
                      <a-input :value="$filterDictTextByCache('yn', formByIndex.isScoreCorrection)" readOnly></a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="11">
                    <a-form-model-item label="是否与上级共享评分" prop="isSharedScore">
                      <a-input :value="$filterDictTextByCache('yn', formByIndex.isSharedScore)" readOnly></a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="11">
                    <a-form-model-item label="上限分值" prop="upperScore">
                      <a-input :value="formByIndex.upperScore" readOnly> </a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="11">
                    <a-form-model-item label="下限分值" prop="lowerScore">
                      <a-input :value="formByIndex.lowerScore" readOnly> </a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="11">
                    <a-form-model-item label="权重 %（M）" prop="weight">
                      <a-input :value="formByIndex.weight" readOnly> </a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="11">
                    <a-form-model-item label="是否禁用" prop="isDisable">
                      <a-input :value="$filterDictTextByCache('yn', formByIndex.isDisable)" readOnly></a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="11">
                    <a-form-model-item label="是否末级" prop="collectWay">
                      <a-input :value="$filterDictTextByCache('yn', formByIndex.collectWay)" readOnly></a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="11">
                    <a-form-model-item label="顺 序" prop="sort">
                      <a-input :value="formByIndex.sort" readOnly></a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="11">
                    <a-form-model-item label="初评分值（N）" prop="firstScore">
                      <a-input :value="formByIndex.firstScore" readOnly> </a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="11">
                    <a-form-model-item label="完成量（L）" prop="finishNumber">
                      <a-input :value="formByIndex.finishNumber" readOnly> </a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="11">
                    <a-form-model-item label="是否允许分发" prop="isDistribution">
                      <a-input :value="$filterDictTextByCache('yn', formByIndex.isDistribution)" readOnly></a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="11">
                    <a-form-model-item label="采集方式" prop="collectionMethod">
                      <a-input
                        :value="$filterDictTextByCache('collectionMethod', formByIndex.collectionMethod)"
                        readOnly
                      ></a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="11" class="col-2">
                    <a-form-model-item label="考核标准" prop="standardAssessment">
                      <a-textarea :value="formByIndex.standardAssessment" readOnly :rows="3"></a-textarea>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-form-model>
            </div>
          </div>
        </a-card>
      </div>
    </a-spin>
    <div class="footerBox" v-if="showType !== '3'">
      <a-button class="btn" @click="handleCancel">取 消</a-button>
      <a-button class="btn" @click="handleOk" style="margin-left: 8px" type="primary">保 存</a-button>
      <a-button class="btn" @click="handleVer" style="margin-left: 8px" type="primary">验证方案</a-button>
    </div>
    <SelIndex ref="selIndex" @ok="selIndexs" :orgCode="orgCode" />
  </j-modal>
</template>

<script>
import SelIndex from './selIndex'

import Api from '@/api/sjsk/performanceService'
import { getDictItemsFromCache } from '@/api/api'

export default {
  name: 'addPlan',
  props: {
    showType: String,
    checkRow: Object,
    visible: Boolean,
    orgCode: String,
  },
  components: {
    SelIndex,
  },
  data() {
    return {
      loading: false,
      isDisabled: false,
      title: null,
      rules: {
        schemeName: [{ required: true, message: '请输入方案名称' }],
        totalScore: [{ required: true, message: '请输入总分' }],
        // sort: [{ required: true, message: '请输入顺序' }],
      },
      rangeOpts: getDictItemsFromCache('appScope'),
      ynOpts: getDictItemsFromCache('yn'),
      indexTypeOpts: getDictItemsFromCache('indicator'),
      collectModeOpts: getDictItemsFromCache('collectionMethod'),
      form: {},
      formByIndex: {},
      checkedIds: [],
      checkIndexs: [],
      treeData: [],
      checkedKeys: [],
      detailItems: [],
    }
  },
  computed: {
    compPlaceholderInput() {
      return this.showType !== '3' ? '请输入' : ''
    },
    compPlaceholderSel() {
      return this.showType !== '3' ? '请选择' : ''
    },
  },
  created() {
    const type = this.showType
    if (type === '1') {
      this.title = '新增方案'
      this.form.status = '0'
    } else if (type === '2') {
      this.title = '编辑方案'
      this.form = this.checkRow
      this.getByIdScheme()
    } else if (type === '3') {
      this.title = '方案详情'
      this.form = this.checkRow
      this.getByIdScheme()
    }
    this.isDisabled = type === '3'
  },
  mounted() {},

  methods: {
    // 选择指标
    onSelIndex() {
      this.$refs.selIndex.show()
    },

    // 选择指标回调
    selIndexs(_list) {
      this.checkIndexs = JSON.parse(JSON.stringify(_list))
      this.checkIndexs.forEach((el) => {
        el.gradeIndicator = el.id
        el.key = el.id
        el.title = el.indicatorName
      })
      this.checkedIds = this.checkIndexs.map((el) => el.id)
      this.treeData = this.listToTreeSimple(this.checkIndexs)
      console.log('this.treeData--', this.treeData)
    },

    // list->tree
    listToTreeSimple(data) {
      /*const arr = []
      data.forEach((item) => {
        const parent = data.find((el) => el.id == item.seniorIndicator)
        if (parent) {
          parent.children = parent.children || []
          item.slots = { default: 'title' }
          parent.children.push(item)
        } else {
          arr.push(item)
        }
      })
      return arr*/
      const treeList = [];
      const dataMap = {};
      if (data && data.length > 0) {
        data.forEach((item) => {
          dataMap[item['id']] = item;
        });
        data.forEach((item) => {
          const parent = dataMap[item['seniorIndicator']];
          if (item.children.length) {
            const pItem = item;
            pItem.children = [];
          }
          if (!parent) {
            treeList.push(item);
            return;
          }
          if (!parent.children) {
            parent.children = [];
          }
          parent.children.push(item);
        });
      }
      return treeList
    },


    // 方案详情
    getByIdScheme() {
      Api.findByIdScheme(this.form.id)
        .then((res) => {
          if (res.success) {
            this.form = res.result.scheme
            this.checkIndexs = res.result.tree
            this.checkIndexs.forEach((el) => {
              el.gradeIndicator = el.id
              el.key = el.id
              el.title = el.indicatorName
              // 待优化
              if(el.children.length) {
                el.children.forEach((ele) => {
                  ele.gradeIndicator = ele.id
                  ele.key = ele.id
                  ele.title = ele.indicatorName
                  if(ele.children.length){
                    ele.children.forEach((elee)=>{
                      elee.gradeIndicator = elee.id
                      elee.key = elee.id
                      elee.title = elee.indicatorName
                    })
                  }
                })
              }
            })
            this.treeData = this.checkIndexs
            if (this.checkIndexs.length) {
              this.formByIndex = this.checkIndexs[0]
            }
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 指标详情
    async indexDetail(_item) {
      if (this.detailItems.some((el) => el.id === _item.id)) {
        this.formByIndex = this.detailItems.find((el) => el.id === _item.id)
      } else {
        this.detailItems.push(_item)
        this.loading = true
        await Api.getIndicatorDetails(_item.id)
          .then((res) => {
            if (res.success) {
              this.formByIndex = res.result
            } else {
              this.$message.error(res.message)
            }
          })
          .finally(() => {
            this.loading = false
          })
      }
      // console.log(this.checkIndexs, _item.key)
      // this.formByIndex = this.checkIndexs.find((el) => el.gradeIndicator === _item.key)
      // console.log('this.formByIndex--', this.formByIndex)
    },

    // 删除
    onDel() {
      console.log('checkedKeys--', this.checkedKeys)
      if (!this.checkedKeys.length) {
        this.$message.warn('请选择指标')
        return
      }
      const filterDel = (arr) => {
        arr.forEach((item, index) => {
          this.checkedKeys.forEach((el) => {
            if (item.id === el) {
              arr.splice(index, 1)
            }
            if (item.children) {
              filterDel(item.children)
            }
          })
        })
        return arr
      }
      this.treeData = filterDel(this.treeData)
      this.checkedIds = Array.from(
        new Set([...new Set(this.checkedIds)].filter((x) => !new Set(this.checkedKeys).has(x)))
      )
      this.checkIndexs = this.checkIndexs.filter((el) => this.checkedIds.includes(el.id))
      if (this.checkedIds.includes(this.formByIndex.id)) {
        this.formByIndex = {}
      }
      console.log('this.checkedIds--', this.checkedIds)
      console.log('this.checkIndexs--', this.checkIndexs)
    },

    // 保存
    handleOk() {
      const that = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!that.checkIndexs.length) {
            that.$message.warn('请添加指标')
            return false
          } else if (!that.checkedKeys.length) {
            that.$message.warn('请选择指标')
            return false
          }
          that.loading = true
          const methodApi = that.form.id ? 'updateByIdScheme' : 'addScheme'
          let params = {
            ...that.form,
            indicatorTree: that.listToTreeSimple(that.checkIndexs),
            indicatorIds: that.checkedKeys,
          }
          Api[methodApi](params)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                that.handleCancel()
              } else {
                that.$message.error(res.message)
              }
            })
            .finally(() => {
              that.loading = false
            })
        } else {
          return false
        }
      })
    },

    // 验证
    handleVer() {
      const that = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!that.checkIndexs.length) {
            that.$message.warn('请添加指标')
            return false
          }
          that.loading = true
          // that.form.listSjskTableIndicatorDto = that.checkIndexs
          // let params = that.form.id ? { ...that.form, gradeIndicator: that.form.id } : that.form
          let params = {
            score:that.form.totalScore,
            tree:that.checkIndexs
          }
          Api.validScheme(params)
            .then((res) => {
              if (res.success) {
                that.$message.success('验证成功')
                that.form.status = '1'
              } else {
                that.$message.error(res.message)
              }
            })
            .finally(() => {
              that.loading = false
            })
        } else {
          return false
        }
      })
    },

    handleCancel() {
      this.$emit('update:visible', false)
    },
  },
}
</script>

<style lang="less" scoped>
.index-card {
  ::v-deep .ant-card-body {
    padding: 0;
  }
  .index-top {
    padding: 20px;
    border-bottom: 1px solid #ddd;
  }
  .index-con {
    display: flex;
    .index-left {
      width: 300px;
      padding: 20px;
      border-right: 1px solid #ddd;
    }
    .index-right {
      flex: 1;
      .tit {
        color: rgba(0, 0, 0, 0.85);
        font-weight: 500;
        font-size: 16px;
        padding-left: 10px;
        background: #eee;
        width: 100%;
        padding: 16px;
        border-top: 1px solid #ddd;
      }
      ::v-deep .ant-form {
        padding-top: 20px;
      }
    }
  }
}
.col-3 {
  width: 100%;
  ::v-deep .ant-form-item-label {
    width: 7%;
  }
  ::v-deep .ant-form-item-control-wrapper {
    width: 67%;
  }
}
.col-2 {
  width: 100%;
  ::v-deep .ant-form-item-label {
    width: 15%;
  }
  ::v-deep .ant-form-item-control-wrapper {
    width: 73%;
  }
}
.footerBox {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  padding-top: 20px;
  border-top: 1px solid #e8e8e8;
}
.content {
  height: 70vh;
  overflow-y: scroll;
}
::v-deep .ant-card-head {
  background: #eee;
}
::v-deep .ant-card-body {
  padding-bottom: 0;
}
</style>
